<?php
/**
 * @Created on 2020/01/15
 * @Author QQ 1026269609@qq.com
*/
namespace app\admin\controller;
use think\Controller;
use think\Db;

class Menu extends Base
{
    public function index(){
		if(request()->isPost()){//排序
			if(is_array($_POST['id'])){
				for($i=0;$i<count($_POST['id']);$i++){
					$id=$_POST['id'][$i];
					$sort=$_POST['sort'][$i];
					db('auth_rule')->where('id',$id)->update(['sort'=>$sort]);
				}
			}
			$this->success('排序成功','Menu/index');
		}else{
			$data=db('auth_rule')->where(['pid'=>0])->order('sort ASC')->select();//顶级菜单
			foreach($data as $k=>$v){//二级菜单
				$data[$k]['two']=db('auth_rule')->where(['pid'=>$v['id']])->order('sort ASC')->select();
				foreach($data[$k]['two'] as $kk=>$vv){//其它菜单
					$data[$k]['two'][$kk]['ree']=db('auth_rule')->where(['pid'=>$vv['id']])->order('sort ASC')->select();
				}
			}
			$this->assign('data',$data);
			return $this->fetch();
		}
    }
    public function addmenu(){
    	if(request()->isPost()){
    		$pid=request()->param('pid');
			$title=request()->param('title');
			$name=request()->param('name');
			$status=request()->param('status');
			$data=['pid'=>$pid,'title'=>$title,'name'=>$name,'status'=>$status];
			$true=db('auth_rule')->insert($data);
			if($true){
				return json(['status'=>1,'message'=>'添加成功']);
			}else{
				return json(['status'=>0,'message'=>'添加失败']);
			}
    	}else{
    		$data=db('auth_rule')->where(['pid'=>0])->order('sort ASC')->select();//顶级菜单
			foreach($data as $k=>$v){//二级菜单
				$data[$k]['two']=db('auth_rule')->where(['pid'=>$v['id']])->order('sort ASC')->select();
			}
			$this->assign('data',$data);
			return $this->fetch();
    	}
    }
    public function editmenu(){
    	if(request()->isPost()){
    		$id=request()->param('id');
    		$pid=request()->param('pid');
			$title=request()->param('title');
			$name=request()->param('name');
			$status=request()->param('status');
			$data=['pid'=>$pid,'title'=>$title,'name'=>$name,'status'=>$status];
			$true=db('auth_rule')->where('id',$id)->update($data);
			if($true){
				return json(['status'=>1,'message'=>'修改成功']);
			}else{
				return json(['status'=>0,'message'=>'修改失败']);
			}
    	}else{
    		$data=db('auth_rule')->where(['pid'=>0])->order('sort ASC')->select();//顶级菜单
			foreach($data as $k=>$v){//二级菜单
				$data[$k]['two']=db('auth_rule')->where(['pid'=>$v['id']])->order('sort ASC')->select();
			}
			$this->assign('data',$data);
			//获取菜单信息
			$id=request()->param('id');
			$info=db('auth_rule')->where('id',$id)->find();
			$this->assign('info',$info);
    		return $this->fetch();
    	}
    }
    public function delmenu(){
    	$id=request()->param('id');
		$info=db('auth_rule')->where('pid',$id)->find();
		if($info){
			return json(['status'=>0,'message'=>'该菜单下存在子项，无法删除']);
		}
		$true=db('auth_rule')->where('id',$id)->delete();
		if($true){
			return json(['status'=>1,'message'=>'删除成功']);
		}else{
			return json(['status'=>0,'message'=>'删除失败']);
		}
    }
}